package com.partsoft.dits;

import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

import com.partsoft.dits.message.MessageEntity;

/**
 * 抽象的消息实体批处理
 */
public abstract class AbstractMessageEntityBatchProcessor {

	public void process(DataIntegrateBatch batch) {
		validateBatch(batch);
		MessageEntity msgEntity = null;
		try {
			if (ClassUtils.isAssignableValue(MessageEntity.class, batch.getInputParameter())) {
				msgEntity = (MessageEntity) batch.getInputParameter();
			}  else {
				throw new IllegalArgumentException(String.format("处理参数不受支持(仅支持实现MessageEntity接口的数据实体)。"));
			}
		} catch (Throwable e) {
			batch.setException(new IllegalArgumentException(String.format("传入的处理参数错误：%s", e.getMessage()), e));
			return;
		}
		try {
			batch.setResult(doProcess(batch.getDataDescriptor(), msgEntity, batch.getAccepter()));
		} catch (Throwable e) {
			batch.setException(e);
		}
	}
	
	protected abstract Object doProcess(DataEdgeDescriptor dataDescriptor, MessageEntity msgEntity, DescriptorAccepter<EdgeDescriptor> accepter);
	
	protected void validateBatch(DataIntegrateBatch batch)  {
		Assert.notNull(batch);
		Assert.notNull(batch.getDataDescriptor());
		Assert.isTrue(!batch.isProcessed(), "已经被处理。");
		Assert.notNull(batch.getInputParameter(), "必须设置输入参数。");
	}

}
